package cn.gz.demo.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Outline
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.View
import android.view.ViewOutlineProvider
import androidx.core.app.ActivityCompat
import androidx.databinding.DataBindingUtil
import cn.gz.demo.R
import cn.gz.demo.databinding.MainBinding
import cn.gz.demo.service.SocketService
import cn.gz.demo.ui.animation.AnimationSetActivity
import cn.gz.demo.ui.base.BaseActivity
import cn.gz.demo.ui.calendar.CalendarActivity
import cn.gz.demo.ui.calendar.CalendarYsActivity
import cn.gz.demo.ui.comment.PingLunActivity
import cn.gz.demo.ui.coordinatorlayout.CoordinatorLayoutActivity
import cn.gz.demo.ui.guide.GuideCommonActivity
import cn.gz.demo.ui.oss.AliOssActivity
import cn.gz.demo.ui.pic.PicMainActivity
import cn.gz.demo.ui.recylerview_header.RecylerViewHeaderActivity
import cn.gz.demo.ui.task.MsgQueueActivity
import cn.gz.demo.ui.xd.RecylerViewXdActivity
import cn.gz.demo.ui.xd.TwoXdActivity
import cn.gz.demo.utils.IntentUtil
import cn.gz.demo.utils.glide.BlurTransformation
import cn.gz.demo.utils.glide.GlideUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import pub.devrel.easypermissions.EasyPermissions
import pub.devrel.easypermissions.EasyPermissions.PermissionCallbacks
import java.text.ParsePosition
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : BaseActivity(), View.OnClickListener, PermissionCallbacks {
    private var binding: MainBinding? = null
    private var handler: Handler? = null
    private var fromType = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
        initEasypermissions()
        initView()
    }

    @SuppressLint("NewApi")
    private fun initView() {
        binding?.titleLayout?.titleBack?.visibility = View.GONE
        binding?.titleLayout?.titleName?.text = "首页"
        binding?.btnSwiperefreshlayout?.setOnClickListener(this)
        binding?.btnSwiperefreshLoadingMore?.setOnClickListener(this)
        binding?.btnRecyclerview?.setOnClickListener(this)
        binding?.btnTablayout?.setOnClickListener(this)
        binding?.btnTablayoutViewpager?.setOnClickListener(this)
        binding?.btnBannerMe?.setOnClickListener(this)
        binding?.btnBannerOther?.setOnClickListener(this)
        binding?.btnCodelayout?.setOnClickListener(this)
        binding?.btnViewpager?.setOnClickListener(this)
        binding?.btnRecylerview?.setOnClickListener(this)
        binding?.btnAlioss?.setOnClickListener(this)
        binding?.btnDatepicker?.setOnClickListener(this)
        binding?.btnDrawerlayout?.setOnClickListener(this)
        binding?.btnCoordinatorlayout?.setOnClickListener(this)
        binding?.btnDialog?.setOnClickListener(this)
        binding?.btnPicture?.setOnClickListener(this)
        binding?.btnRecylerviewHeader?.setOnClickListener(this)
        binding?.btnAnimation?.setOnClickListener(this)
        binding?.btnGuide?.setOnClickListener(this)
        binding?.btnTextClick?.setOnClickListener(this)
        binding?.btnXd?.setOnClickListener(this)
        binding?.btnPopup?.setOnClickListener(this)
        binding?.btnScrollviewImage?.setOnClickListener(this)
        binding?.btnTablayoutViewpagerRecyclerview?.setOnClickListener(this)
        binding?.btnSystem?.setOnClickListener(this)
        binding?.btnFy?.setOnClickListener(this)
        binding?.btnBase64?.setOnClickListener(this)
        binding?.btnDitu?.setOnClickListener(this)
        binding?.btnExport?.setOnClickListener(this)
        binding?.btnCircle?.setOnClickListener(this)
        binding?.btnEdit?.setOnClickListener(this)
        binding?.btnGreendao?.setOnClickListener(this)
        binding?.btnScrollview?.setOnClickListener(this)
        binding?.btnTwoXd?.setOnClickListener(this)
        binding?.btnScrollviewXd?.setOnClickListener(this)
        binding?.btnImageOperation?.setOnClickListener(this)
        binding?.btnCoordinatorScrollview?.setOnClickListener(this)
        binding?.btnWebsocket?.setOnClickListener(this)
        binding?.btnBottomsheet?.setOnClickListener(this)
        binding?.btnSharesList?.setOnClickListener(this)
        binding?.btnCustomTime?.setOnClickListener(this)
        binding?.btnViewOpenClose?.setOnClickListener(this)
        binding?.btnSign?.setOnClickListener(this)
        binding?.btnScheduledexecutorservice?.setOnClickListener(this)
        binding?.btnCardview?.setOnClickListener(this)
        binding?.btnPinglun?.setOnClickListener(this)
        binding?.btnKotlin?.setOnClickListener(this)
        binding?.image?.setOnClickListener(this)
        binding?.btnPic?.setOnClickListener(this)
        binding?.btnNestscrollviewTablayout?.setOnClickListener(this)
        binding?.btnNestscrollviewViewpager?.setOnClickListener(this)
        binding?.btnNumber?.setOnClickListener(this)
        binding?.btnLine?.setOnClickListener(this)
        binding?.btnScore?.setOnClickListener(this)
        binding?.btnCalendar?.setOnClickListener(this)
        binding?.btnMsgQueue?.setOnClickListener(this)
        //        GlideUtil?.loadPicNoCash(context, "https://dev?.gdlcapp?.com/datamgr/upload/file/public/download?uri=/bpm/2020/05/20/ifyv9do4l1i1amuq4ax5?.png", binding?.image);
//        Bitmap bitmapOne = BitmapFactory?.decodeResource(context?.getResources(), R?.mipmap?.pic_leadpage_1);
//        Bitmap bitmapTwo = BitmapFactory?.decodeResource(context?.getResources(), R?.mipmap?.pic_yindao);
//        Bitmap bitmap = BitmapUtils?.combineImage(bitmapOne, bitmapTwo);
////        Bitmap bitmap = BitmapUtils?.mergeThumbnailBitmap_1(bitmapOne, bitmapTwo, 255);
//        binding?.image?.setImageBitmap(bitmap);
        val intent = Intent(context, SocketService::class?.java)
        startService(intent)

        binding?.imageLayout?.setOutlineProvider(object : ViewOutlineProvider() {
            override fun getOutline(view: View, outline: Outline) {
                outline.setRoundRect(0, 0, view.width, view.height, 15f)
            }
        })
        binding?.imageLayout?.setClipToOutline(true)

        GlideUtil.loadPicNoCash(context, "https://impress-file-server.oss-cn-shenzhen.aliyuncs.com/5e313bbbf2874926a449620f3b508d89.png", binding?.image)
    }


    fun loadPIc() {
        ++fromType;
        if (fromType % 2 == 0) {
            var options = RequestOptions() //                .centerCrop()
//                .placeholder(R.drawable.default_icon)
                    .error(R.mipmap.error_icon)
                    .transform(BlurTransformation(context))
//                .transform(RoundedCornersTransform(context, 10f, 20f, 5f, 35f))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)

            Glide.with(context).clear(binding?.image)
            Glide.with(context)
                    .load("https://lcapp-test.oss-cn-shenzhen.aliyuncs.com/image/2019/02/27/0nedtspe6uqqzntnfufm.png")
                    .apply(options)
                    .into(binding?.image)
        } else {
            var options = RequestOptions() //                .centerCrop()
//                .placeholder(R.drawable.default_icon)
                    .error(R.mipmap.error_icon)
                    .transform(BlurTransformation(context))
                    .override(60, 60)
//                .transform(RoundedCornersTransform(context, 10f, 20f, 5f, 35f))
                    .diskCacheStrategy(DiskCacheStrategy.NONE)

            Glide.with(context).clear(binding?.image)
            Glide.with(context)
                    .load("https://lcapp-test.oss-cn-shenzhen.aliyuncs.com/image/2019/02/27/0nedtspe6uqqzntnfufm.png")
                    .apply(options)
                    .into(binding?.image)
        }
    }

    fun parseStringToDate(msg: String?, parse: String?): Date {
        val formatter = SimpleDateFormat(parse)
        val pos = ParsePosition(0)
        return formatter?.parse(msg, pos)
    }

    override fun onClick(v: View) {
        val id = v?.id
        when (id) {
            R.id.btn_swiperefreshlayout -> IntentUtil.startActivity(context, SwipeRefreshLayoutActivity::class.java)
            R.id.btn_swiperefresh_loading_more -> IntentUtil.startActivity(context, SwipeRefreshLoadingMoreActivity::class.java)
            R.id.btn_recyclerview -> IntentUtil.startActivity(context, RecyclerViewActivity::class.java)
            R.id.btn_tablayout -> IntentUtil.startActivity(context, TabLayoutActivity::class.java)
            R.id.btn_tablayout_viewpager -> IntentUtil.startActivity(context, TabLayoutViewPagerActivity::class.java)
            R.id.btn_tablayout_viewpager_recyclerview -> IntentUtil.startActivity(context, TabLayoutViewPager2Activity::class.java)
            R.id.btn_banner_me -> IntentUtil.startActivity(context, BannerMeActivity::class.java)
            R.id.btn_banner_other -> IntentUtil.startActivity(context, BannerOtherActivity::class.java)
            R.id.btn_viewpager -> IntentUtil.startActivity(context, ViewPagerActivity::class.java)
            R.id.btn_recylerview -> IntentUtil.startActivity(context, RollRecylerViewActivity::class.java)
            R.id.btn_alioss -> IntentUtil.startActivity(context, AliOssActivity::class.java)
            R.id.btn_datepicker -> IntentUtil.startActivity(context, DatePickerActivity::class.java)
            R.id.btn_drawerlayout -> IntentUtil.startActivity(context, DrawerLayoutActivity::class.java)
            R.id.btn_coordinatorlayout -> IntentUtil.startActivity(context, CoordinatorLayoutActivity::class.java)
            R.id.btn_dialog -> IntentUtil.startActivity(context, DialogActivity::class.java)
            R.id.btn_picture -> IntentUtil.startActivity(context, PictureActivity::class.java)
            R.id.btn_recylerview_header -> IntentUtil.startActivity(context, RecylerViewHeaderActivity::class.java)
            R.id.btn_viewswitcher -> IntentUtil.startActivity(context, ViewSwitcherActivity::class.java)
            R.id.btn_animation -> IntentUtil.startActivity(context, AnimationSetActivity::class.java)
            R.id.btn_guide -> IntentUtil.startActivity(context, GuideCommonActivity::class.java)
            R.id.btn_text_click -> IntentUtil.startActivity(context, TextClickActivity::class.java)
            R.id.btn_xd -> IntentUtil.startActivity(context, RecylerViewXdActivity::class.java)
            R.id.btn_popup -> IntentUtil.startActivity(context, PopupActivity::class.java)
            R.id.btn_scrollview_image -> IntentUtil.startActivity(context, ScrollViewImageActivity::class.java)
            R.id.btn_system -> IntentUtil.startActivity(context, SystemActivity::class.java)
            R.id.btn_fy -> IntentUtil.startActivity(context, FyActivity::class.java)
            R.id.btn_base64 -> IntentUtil.startActivity(context, Base64Activity::class.java)
            R.id.btn_ditu -> IntentUtil.startActivity(context, DituActivity::class.java)
            R.id.btn_export -> IntentUtil.startActivity(context, ExportActivity::class.java)
            R.id.btn_circle -> IntentUtil.startActivity(context, CircleActivity::class.java)
            R.id.btn_edit -> IntentUtil.startActivity(context, EditActivity::class.java)
            R.id.btn_greendao -> IntentUtil.startActivity(context, GreenDaoActivity::class.java)
            R.id.btn_scrollview -> IntentUtil.startActivity(context, ScrollViewActivity::class.java)
            R.id.btn_two_xd -> IntentUtil.startActivity(context, TwoXdActivity::class.java)
            R.id.btn_scrollview_xd -> IntentUtil.startActivity(context, StickActivity::class.java)
            R.id.btn_image_operation -> IntentUtil.startActivity(context, ImageOperationActivity::class.java)
            R.id.btn_coordinator_scrollview -> IntentUtil.startActivity(context, CoordinatorScrollviewActivity::class.java)
            R.id.btn_websocket -> IntentUtil.startActivity(context, WebSocketActivity::class.java)
            R.id.btn_bottomsheet -> IntentUtil.startActivity(context, BottomSheetActivity::class.java)
            R.id.btn_shares_list -> IntentUtil.startActivity(context, ShareListActivity::class.java)
            R.id.btn_custom_time -> IntentUtil.startActivity(context, CustomTimeActivity::class.java)
            R.id.btn_view_open_close -> IntentUtil.startActivity(context, ViewOpenCloseActivity::class.java)
            R.id.btn_sign -> IntentUtil.startActivity(context, SignActivity::class.java)
            R.id.btn_scheduledexecutorservice -> IntentUtil.startActivity(context, ScheduledExecutorServiceActivity::class.java)
            R.id.btn_cardview -> IntentUtil.startActivity(context, CardViewActivity::class.java)
            R.id.btn_pinglun -> IntentUtil.startActivity(context, PingLunActivity::class.java)
            R.id.btn_kotlin -> IntentUtil.startActivity(context, KotlinActivity::class.java)
            R.id.btn_pic -> IntentUtil.startActivity(context, PicMainActivity::class.java)
            R.id.btn_nestscrollview_tablayout -> IntentUtil.startActivity(context, RecyclerviewTablayout2Activity::class.java)
            R.id.btn_nestscrollview_viewpager -> IntentUtil.startActivity(context, ViewPagerTablayoutActivity::class.java)
            R.id.btn_number -> IntentUtil.startActivity(context, NumberActivity::class.java)
            R.id.btn_line -> IntentUtil.startActivity(context, LineActivity::class.java)
            R.id.btn_score -> IntentUtil.startActivity(context, ScoreActivity::class.java)
            R.id.btn_calendar -> IntentUtil.startActivity(context, CalendarActivity::class.java)
            R.id.btn_msg_queue -> IntentUtil.startActivity(context, MsgQueueActivity::class.java)
            R.id.image -> {
                Glide.with(context).clear(binding?.image);
                binding?.image?.refreshDrawableState()
                binding?.image?.setBackgroundResource(R.mipmap.pic_my_touxiang_woman)
            }
            R.id.btn_codelayout -> { //                RequestOptions options = new RequestOptions()
//                        .skipMemoryCache(true)
//                        .diskCacheStrategy(DiskCacheStrategy.NONE);
//                Glide.with(context)
////                        .load("https://dev.gdlcapp.com/usermgr/public/img/verify/Code?t=1&s=jf_android&deviceId=860410032098782&c=1577950081623")
//                        .load("https://ruqi-busi-company-1258234669.cos.ap-guangzhou.myqcloud.com/000e985c-68c7-45bb-8244-4bcd6f5378fc/1570589193314.jpg?q-sign-algorithm=sha1&q-ak=AKIDhlBHXbLK8nnQsgKx2y_I_zIAYhKuL9d8f3BivglrNHxpJ1UuoaJcSPV2lny5GdYu&q-sign-time=1577952457;1577956057&q-key-time=1577952457;1577956057&q-header-list=&q-url-param-list=&q-signature=751a2f0097cda435095b8968a82c35c30e95ba63&x-cos-security-token=B2sId9oY0aKXu8fG7EpXkdSZRJcbHByA3d184eebaeec7e124d7b1b7281343778mejKlvEoTDn-s07vaSTIHZpf9-cUP2dA5v8nXMuldxyiXNz9WRxBhKSxksIGzl3srip1Kbc83m8NzsYxgmOYnDr6dGWdzvd0X8SSTE8Pegst1tXcJoC8CbZHmFhyQY4PHCm7luyAr5qiy-hI0aLmsRyUIXnrgxvmVO59dp01AY8")
//                        .apply(options).into(binding.image);

//                GlideUtil.loadPicNoCash(context, R.mipmap.map_voice_icon, binding?.image)
                loadPIc()
            }
        }
    }

    private fun initEasypermissions() {
        val permissions = arrayOf(
                Manifest.permission.CAMERA,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.SEND_SMS,
                Manifest.permission.READ_SMS,
                Manifest.permission.RECEIVE_SMS,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_COARSE_LOCATION
        )
//        if (EasyPermissions.hasPermissions(this, *permissions)) {
//            Log.e("Lyz", "..........hasPermissions................")
//        } else {
//            Log.e("Lyz", "..........requestPermissions................")
//            EasyPermissions.requestPermissions(this, "点击确定应用需要获取的权限", 101, *permissions)
//        }
        ActivityCompat.requestPermissions(this, permissions, 101);
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    //成功
    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
        if (perms != null && perms.size > 0) {
            for (i in perms.indices) {
                Log.e("Lyz", "...ok...perms......." + i + "....." + perms[i])
            }
            Log.e("Lyz", "..........onPermissionsGranted................")
        }
    }

    //失败
    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (perms != null && perms?.size > 0) {
            for (i in perms?.indices) {
                Log.e("Lyz", "..faild....perms......." + i + "....." + perms[i])
            }
            Log.e("Lyz", "..........onPermissionsDenied................")
        }
    }
}